package streaming

import (
	"fmt"
	"io"
	"os"
	"protobuf-learn/proto"

	"github.com/google/uuid"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type FileService struct {
	proto.UnimplementedFileServiceServer
}

func (s *FileService) DownloadFile(req *proto.DownloadFileRequest, stream proto.FileService_DownloadFileServer) error {
	// check if the name is empty in the request
	if req.GetName() == "" {
		status.Errorf(codes.InvalidArgument, "file name cannot be empty")
	}
	// open the file
	file, err := os.Open(req.GetName())
	if err != nil {
		if os.IsNotExist(err) {
			// check the file is not found, return not found otherwise
			status.Errorf(codes.NotFound, "file not found")
		}
		return err
	}

	// read the file in chunks of 5KB
	const buffSize = 5 * 1024
	buff := make([]byte, buffSize)
	for {
		// stream each chunk to the client
		len, err := file.Read(buff)
		if err != nil {
			if err == io.EOF {
				return nil // close the server stream
			}
			return status.Error(codes.Internal, "error readding file: "+err.Error())
		}

		err = stream.Send(&proto.DownloadFileResponse{
			Content: buff[:len],
		})
		if err != nil {
			return err
		}
	}
}
func (s *FileService) UplodFile(stream proto.FileService_UplodFileServer) error {
	// generate the file name
	fileName := fmt.Sprintf("%s.png", uuid.New().String())
	// create a file
	file, err := os.Create(fileName)
	if err != nil {
		return status.Error(codes.Internal, "error creating file: "+err.Error())
	}
	defer file.Close()
	// receive chunks from client
	for {
		res, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				return stream.SendAndClose(&proto.UplodFileResponse{
					Name: fileName,
				})
			}
			return err
		}

		// write chunk to  file
		if _, err := file.Write(res.Content); err != nil {
			return status.Error(codes.Internal, "error writing to file: "+err.Error())
		}
	}
}
